package org.helgoboss.maven_commandlet_client;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.helgoboss.jvm_commandlet_client.JvmCommandletClient;

/**
 * Goal to execute a commandlet. 
 * 
 * @goal execute-commandlet
 */
public class MavenCommandletClient extends AbstractMojo {

	/**
	 * @parameter expression="${project}"
	 */
	MavenProject project;
	
	/**
	 * @parameter
	 * @required
	 */
	String commandletId;
	
	/**
	 * @parameter default-value="${project.basedir}"
	 */
	File workingDirectory;
	
	/**
	 * @parameter
	 */
	List<String> arguments;
	

	public void execute() throws MojoExecutionException, MojoFailureException {
		JvmCommandletClient client = new JvmCommandletClient();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] emptyInput = new byte[0];
		ByteArrayInputStream input = new ByteArrayInputStream(emptyInput);
		String[] argumentArray;
		if (arguments == null) {
			argumentArray = new String[0];
		} else {
			argumentArray = (String[]) arguments.toArray(new String[0]);
		}
		client.executeCommandlet(commandletId, workingDirectory, argumentArray, input, output);
		getLog().info(output.toString());
	}
}
